package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.model.HqlArgs;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.TagDao;
import tech.yunland.shop.domain.dao.TagGoodsDao;
import tech.yunland.shop.domain.model.Tag;
import tech.yunland.shop.domain.model.TagGoods;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 标签
 *
 * @author 王东阳<350456985@qq.com>
 */

@Service
public class TagService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String DELETE_ENTRIES_HQL = "delete from TagGoods tg where tg.id=?";

    @Autowired
    private TagDao tagDao;
    @Autowired
    private TagGoodsDao tagGoodsDao;

    /**
     * 保存标签信息
     *
     * @param tag
     */
    public void saveOrUpdate(Tag tag) {
        tagDao.saveOrUpdate(tag);

        //清理旧分录
        tagGoodsDao.bulkUpdate(DELETE_ENTRIES_HQL, tag.getId());
        if (tag.getTagGoods() != null) {
            // 保存新分录
            for (TagGoods tagGoods : tag.getTagGoods()) {
                tagGoodsDao.save(tagGoods);
            }
        }
    }

    /**
     * 保存标签商品对应关系
     *
     */
    public void saveTagGoods(TagGoods tagGoods) {
        tagGoodsDao.saveOrUpdate(tagGoods);
    }

    /**
     * 删除标签
     *
     * @param id
     */
    public void del(String id) {
        // 清理 TagGoods
        String delHql = "delete from TagGoods tg where tg.tag.id=?";
        tagGoodsDao.bulkUpdate(delHql, id);

        tagDao.delete(id);
    }

    /**
     * 读取标签
     *
     * @param id
     * @return
     */
    public Tag get(String id) {
        return tagDao.get(id);
    }

    /**
     * 查找指定机构下的商品标签
     *
     * @param name
     * @param organId
     * @return
     */
    public List<Tag> getList(String name, String organId) {
        name = StringUtils.trim(name);
        organId = StringUtils.trim(organId);

        if (name == null & organId == null) {
            return null;
        }

        DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);

        if (name != null) {
            criteria.add(Restrictions.eq("name", name));
        }

        if (organId != null) {
            criteria.createCriteria("organ").add(Restrictions.eq("id", organId));
//			criteria.createCriteria("organ").add(Restrictions.idEq(organId));
        }


        return tagDao.findByCriteria(criteria);
    }

    /**
     * 根据条件生成 hql 语句 tag
     *
     * @param param
     * @param tagIds
     * @param organIds
     * @return
     */
    private HqlArgs genHqlArgs(String param, List<String> organIds) {
        param = StringUtils.trimToEmpty(param);
        Map<String, Object> args = new HashMap<String, Object>();

        String hql = "from Tag g where 1=1";
        //按照名称查询 查询的是标签表
        if (StringUtils.isNotBlank(param)) {
            hql = " from Tag g where g.name like :arg or g.spell like :arg";
            args.put("arg", "%" + param + "%");
        }
        //按组织查询 显示当前组织下的标签
        if (organIds != null && organIds.size() > 0) {
            if (organIds.size() == 1) {
                hql += " and g.organ.id = :organIds";
                args.put("organIds", organIds.get(0));
            }
            else {
                hql += " and g.organ.id in :organIds";
                args.put("organIds", organIds);
            }
        }

        return new HqlArgs(hql, args);
    }

    /**
     * 根据条件生成 hql 语句 TagGoods
     *
     * @param goodsId
     * @param tagId
     * @return
     */
    private HqlArgs genHqlArgsTG(String goodsId, String tagId) {

        Map<String, Object> args = new HashMap<String, Object>();

        String hql = "from TagGoods tg where 1=1 ";
        if (goodsId != null) {
            hql += " and tg.goods.id = :goodsId";
            args.put("goodsId", goodsId);
        }

        if (tagId != null) {
            hql += " and tg.tag.id = :tagId";
            args.put("tagId", tagId);
        }
        
        

        return new HqlArgs(hql, args);
    }

    /**
     * 根据入参查询结果数量 tag
     *
     * @param param
     * @param organIds
     * @return
     */
    public int getResultSize(String param, List<String> organIds) {

        HqlArgs hqlArgs = genHqlArgs(param, organIds);
//        String hql = "select count(*) " + hqlArgs.getHql();
//        return tagDao.getResultSize(hql, hqlArgs.getArgs());
        return (int) tagDao.getCount(hqlArgs.getHql(), hqlArgs.getArgs());
    }

    /**
     * 根据入参查询结果数量 TagGoods
     *
     * @param goodsId
     * @param tagId
     * @return
     */
    public int getResultSizeTG(String goodsId, String tagId) {
        HqlArgs hqlArgs = genHqlArgsTG(goodsId, tagId);
        return tagGoodsDao.findByNamedParam(hqlArgs.getHql(), hqlArgs.getArgs()).size();
    }

    /**
     * 根据入参查询结果集 tag
     *
     * @param param
     * @param tagIds
     * @param startIndex
     * @param length
     * @param organIds
     * @return
     */
    public List<Tag> getResultInfos(String param, Integer startIndex, Integer length, List<String> organIds) {


        HqlArgs hqlArgs = genHqlArgs(param, organIds);
        String hql = "select g " + hqlArgs.getHql() + " order by g.rate desc";

        return tagDao.findByNamedParam(hql, startIndex, length, hqlArgs.getArgs());
    }

    /**
     * 根据入参查询结果集 tagGoods
     *
     * @param goodsId
     * @param tagId
     * @param startIndex
     * @param length
     * @return
     */
    public List<TagGoods> getResultInfoTG(String goodsId, String tagId, Integer startIndex, Integer length) {
        HqlArgs hqlArgs = genHqlArgsTG(goodsId, tagId);
        String hql = "select tg " + hqlArgs.getHql();

        return tagGoodsDao.findByNamedParam(hql, startIndex, length, hqlArgs.getArgs());
    }
}
